#include "utils/service_discovery.hpp"
#include <workflow/WFTaskFactory.h>
#include <workflow/WFFacilities.h>
#include <nlohmann/json.hpp>
#include <iostream>
#include <vector>
#include <cstdlib> // for rand()
#include <ctime>   // for time()

using json = nlohmann::json;

ServiceDiscovery::ServiceDiscovery(const std::string& consul_uri) : m_consulUri(consul_uri) {
    // 初始化随机数种子，用于负载均衡
    srand(time(nullptr));
}

std::string ServiceDiscovery::discoverService(const std::string& service_name) {
    // --- 核心修正：使用正确的 Catalog API 端点 ---
    std::string url = m_consulUri + "/v1/catalog/service/" + service_name;
    
    std::string service_address;
    WFFacilities::WaitGroup wg(1);
    
    WFHttpTask *task = WFTaskFactory::create_http_task(url, 0, 0, 
        [&service_address, &wg, service_name](WFHttpTask *task) {
            protocol::HttpResponse *resp = task->get_resp();
            int state = task->get_state();

            if (state == WFT_STATE_SUCCESS && resp && std::string(resp->get_status_code()) == "200") {
                const void *body;
                size_t len;
                resp->get_parsed_body(&body, &len);
                try {
                    json services = json::parse((const char*)body, (const char*)body + len);
                    if (!services.is_array() || services.empty()) {
                        std::cerr << "[Discovery] WARN: No instances found for service '" << service_name << "'." << std::endl;
                    } else {
                        // 简单的随机负载均衡
                        int index = rand() % services.size();
                        const auto& service_info = services[index];
                        
                        // 从 Catalog API 返回的 JSON 中正确地获取地址和端口
                        std::string address = service_info["ServiceAddress"].get<std::string>();
                        int port = service_info["ServicePort"].get<int>();

                        service_address = address + ":" + std::to_string(port);
                    }
                } catch (const json::exception& e) {
                    std::cerr << "[Discovery] ERROR: Failed to parse Consul response for " << service_name << ". " << e.what() << std::endl;
                }
            } else {
                 std::cerr << "[Discovery] ERROR: Failed to query Consul for service '" << service_name << "'. State: " << state << std::endl;
            }
            wg.done();
        });

    task->start();
    wg.wait(); // 同步等待 HTTP 请求完成

    return service_address;
}
